import React, { Component } from 'react';
import { base, toast, formDownload,getMultiLang, gzip, createPage } from 'nc-lightapp-front';
const { NCButton: Button, NCUpload, NCIcon:Icon, NCLoading:Loading, NCModal: Modal, NCForm, NCDiv } = base;
const { NCFormItem: FormItem } = NCForm;
import {StrUtils} from '../../utils/StrUtils'

import { RadioItem } from '../FormItems';
import './index.less'

/**
 * 
 * 导入导出弹框
 * handleRefresh 刷新
 * tmpletType: import export assExport (判断弹框展示的类型)
 * impData： 导入导出 需要的数据
 * visible：是否显示弹框
 * 
 */

const formItemLayout = { labelXs:4, labelSm:4, labelMd:4, xs:8, md:8, sm:8 };
const formItemParam = { inline:true, showMast:false, isRequire:true, method:"change" };

export default class ImportFile extends Component {
    constructor(props) {
        super(props);
        this.state = {
            json:{},
            listItem: {
                importPattern: { display: '', value: 'true' },
                isroundup: { display: '', value: 'true' },
                savePattern: { display: '', value: 'true' },
                exportContent: { display: '', value: 'true' },
                incloudCode: { display: '', value: 'false' }
            },
        };
        this.impImpletData = []
        this.expImpletData = []
        this.assExportData = []
    }
    getImpImpletData = () => {
        let impImpletData = [
            { 
                itemName: this.state.json['publiccomponents-000032'], 
                itemType: 'radio', 
                itemKey: 'importPattern', 
                itemChild: [
                    { value: 'true', label: this.state.json['publiccomponents-000033'] }, 
                    { value: 'false', label: this.state.json['publiccomponents-000034'] }
                ] 
            },/* 国际化处理： 导入方式:,按名称,按编码*/
            { 
                itemName: this.state.json['publiccomponents-000035'], 
                itemType: 'radio', 
                itemKey: 'isroundup', 
                itemChild: [
                    { value: 'true', label: this.state.json['publiccomponents-000036'] }, 
                    { value: 'false', label: this.state.json['publiccomponents-000037'] }
                ] 
            },/* 国际化处理： 精度处理:,四舍五入,舍位*/
            { 
                itemName: this.state.json['publiccomponents-000038'], 
                itemType: 'radio', 
                itemKey: 'savePattern', 
                itemChild: [
                    { value: 'true', label: this.state.json['publiccomponents-000039'] }, 
                    { value: 'false', label: this.state.json['publiccomponents-000040'] }
                ] 
            }/* 国际化处理： 导入数据方式:,覆盖,增量*/
        ]
        return impImpletData
    }
    getExpImpletData = () => {
        let expImpletData = [
            { 
                itemName: this.state.json['publiccomponents-000041'], 
                itemType: 'radio', 
                itemKey: 'exportContent', 
                itemChild: [
                    { value: 'true', label: this.state.json['publiccomponents-000042'] }, 
                    { value: 'false', label: this.state.json['publiccomponents-000043'] }
                ] 
            },/* 国际化处理： 导出内容:,样式+数据,样式*/
            { 
                itemName: this.state.json['publiccomponents-000044'], 
                itemType: 'radio', itemKey: 'incloudCode', 
                itemChild: [
                    { value: 'false', label: this.state.json['publiccomponents-000006'] }, { value: 'true', label: this.state.json['publiccomponents-000005'] }
                ] 
            },/* 国际化处理： 档案包含编码列:,否,是*/
            // { itemName: '覆盖规则:', itemType: 'radio', itemKey: 'savePattern', itemChild: [{ value: 'true', label: '覆盖原内容' }, { value: 'false', label: '增加新页签' }] }
        ]
        return expImpletData
    }
    getAssExportData = () => {
        let assExportData = [
            { 
                itemName: this.state.json['publiccomponents-000090'], 
                itemType: 'radio', 
                itemKey: 'importPattern', 
                itemChild: [
                    { value: 'true', label: this.state.json['publiccomponents-000033'] },
                    { value: 'false', label: this.state.json['publiccomponents-000034'] }
                ] 
            }/* 国际化处理： 导出方式:,按名称,按编码*/
        ]
        return assExportData
    }
    // 整合接口需要数据： 弹框数据 和 父级数据 整合成一个新数据
    consData(tmpletType){
        let { listItem } = this.state
        let {impData,assExport} = this.props
        let baseData, newData
        if(tmpletType==='import'){
            baseData = {
                importPattern: '',
                isroundup: '',
                savePattern: ''
            }
        } else {
            if(assExport){
                baseData = {
                    importPattern: ''
                }
            }else{
                baseData = {
                    exportContent: '',
                    incloudCode: ''
                }
            }
            
        }
        for (const key in baseData) {
            if (baseData.hasOwnProperty(key)) {
                baseData[key] = listItem[key].value
            }
        }
        newData = Object.assign(baseData,impData)
        return newData
    }
    // 打开弹框
	show = (title) => {
        this.props.modal.show('excel', title);
    }
    // 关闭弹框
    close = () => {
        this.props.modal.close('excel');
    }
    // 导出
    downLoad = (tmpletType) => {
        let data = this.consData(tmpletType)
        if(data && data.action) {
            let action = data.action
            formDownload({
                params:{param:JSON.stringify(data)},
                url: action,
                enctype:2
            });
            this.close();
        }   
    }

    // 显示Loading
    showLoading = (container) =>{
        container.className = 'nc-loading-show-delay';
        ReactDOM.render(<Loading show={true} fullScreen container={container} />, container);
    }
    // 隐藏Loading 
    hideLoading = (container) => {
        container.className = '';
        ReactDOM.unmountComponentAtNode(container);
    }
    
    // 导入
    uploadData = (tmpletType) => {
        let self = this
        let data = self.consData(tmpletType)
        let div = window.document.createElement('div');
        window.document.body.appendChild(div);
        let propsData
        if(data && data.action){
            let action = data.action
            propsData = {
                name: 'file',
                data:{
                        param:JSON.stringify(data)
                    },
                action: action,
                accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                headers: {
                  authorization: 'authorization-text',
                },
                NcUploadOnChange(info) {
                    if(info.file.status == 'uploading'){
                        self.showLoading(div)
                    } 
                    // else {
                    //     self.hideLoading(div)
                    // }
                    if (info.file.status === 'done') {
                        //记录成功或失败信息
                        self.hideLoading(div)
                        let gziptools = new gzip();
                        
                        let response = info.file.response;
                        if(typeof response == 'string'){
                            if(!StrUtils.isJSONStr(response)){
                                response = gziptools.unzip(response);
                            }
                            response = JSON.parse(response);
                        }
                        // let response = typeof info.file.response == 'string' ? gziptools.unzip(info.file.response): info.file.response;

                        if(response.success){
                            toast({ content: self.state.json['publiccomponents-000051'], color: 'success' });/* 国际化处理： 导入成功*/
                            
                            setTimeout(() => self.close(), 1000 );
                            setTimeout(() => self.props.handleRefresh(), 1000 );                           
                        }else{                      
                            if(response.error){
                                if(response.error.message){
                                    let errMessage = response.error.message 
                                    toast({ content: errMessage, color: 'danger' })
                                    self.close()
                                }
                            }
                        }
                    } else if (info.file.status === 'error') {
                        toast({ content: self.state.json['publiccomponents-000052'], color: 'danger' })/* 国际化处理： 导入失败*/
                    }
                }
            }
        }
        return propsData
    }

    componentWillMount(){
		let callback= (json) =>{
            this.setState({
              json: json
			},()=>{
                //initTemplate.call(this, this.props);
                this.impImpletData = this.getImpImpletData()
                this.expImpletData = this.getExpImpletData()
                this.assExportData = this.getAssExportData()
            })
        }
		getMultiLang({moduleId:'publiccomponents',domainName:'gl',currentLocale:'simpchn',callback});
    }
    componentWillReceiveProps(nextProps){
        let {optItems, data} = nextProps;
        if(optItems && data){
            this.setState({optItems, data});
        }

    }
    componentDidMount(){
        this.props.ImportFileRef && this.props.ImportFileRef(this);
    }

    renderRadio = (listItem, item) =>{
        return (
            <FormItem
                {...formItemLayout}
                {...formItemParam}
                labelName={item.itemName}
            //  change={self.handleGTypeChange.bind(this, 'contracttype')}
            >
                <RadioItem
                    name={item.itemKey}
                    type="customer"
                    defaultValue={listItem[item.itemKey].value ? listItem[item.itemKey].value : 'true'}
                    items={() => {
                        return (item.itemChild)
                    }}
                    onChange={(v) => {
                        listItem[item.itemKey].value = v
                        this.setState({
                            listItem
                        })
                    }}
                />
            </FormItem>
        )
    }
    
    renderForm = (tmpletType,listItem,assExport) =>{
        
        let tempData = (tmpletType==='import') ? this.impImpletData : assExport ? this.assExportData : this.expImpletData
        return (
            tempData.map((item, i) => {
                switch (item.itemType) {
                    case 'radio':
                        return this.renderRadio(listItem, item)                      
                    // case 'select':
                    //     return this.renderSelect(listItem, item)                    
                    default:
                        break;
                }
            })
        )
    }
    modalFooter = () => {
        let { tmpletType } = this.props
        let propsData = (tmpletType==='import') ? this.uploadData(tmpletType): ''
        let modalTitle = (tmpletType==='import') ? this.state.json['publiccomponents-000053'] : this.state.json['publiccomponents-000050'] /* 国际化处理： 导入,导出*/
        let iconClass = (tmpletType==='import') ? 'uf-upload' : 'uf-download'
        return(
            <div>
                {(tmpletType==='import') ?(
                    <div style={{display:'inline-flex'}}>
                    <NCUpload {...propsData}>
                        <Button fieldid='upload' shape="border" colors= 'primary'>
                            <Icon type={iconClass} />{modalTitle}
                        </Button>
                    </NCUpload>
                </div>
                ):(
                    <Button fieldid='download' shape="border" colors= 'primary' onClick={this.downLoad.bind(this)}>
                        <Icon type={iconClass} />{modalTitle}
                    </Button>
                )}
                
                <Button fieldid='cancel' onClick={this.close.bind(this)}>{this.state.json['publiccomponents-000010']}</Button>{/* 国际化处理： 取消*/}
            </div>
        )
    }
    modalContent = () => {
        let { tmpletType,assExport } = this.props
        let { listItem } = this.state
        return(
            <NCDiv fieldid="excel" areaCode={NCDiv.config.FORM}>
                <NCForm className='importform'
                    useRow={true}
                    submitAreaClassName='classArea'
                    showSubmit={false}　>
                    {this.renderForm(tmpletType,listItem,assExport)}
                </NCForm>
            </NCDiv>
        )
    }
    render() {
        let { tmpletType, modal } = this.props
        // let modalTitle = (tmpletType==='import') ? this.state.json['publiccomponents-000053'] : this.state.json['publiccomponents-000050'] /* 国际化处理： 导入,导出*/
        return (
            <div>
                {modal.createModal('excel', {
					title: `EXCEL`, 
					content: this.modalContent(), //弹框内容，可以是字符串或dom
					customBtns: this.modalFooter(), //JSX结构，样式需要自己写 确定
					showCustomBtns: true,//允许自定义footer里的按钮,默认false显示 确定 和 取消 按钮，true是传入自定义的按钮
				})}
            </div>
        )
    }
    
}

// ImportFile = createPage({})(ImportFile)
// export default ImportFile
